import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class Main {

	public static void main2(String[] args) {
		float sampleRate = 8000;
	    int sampleSizeInBits = 8;
	    int channels = 1;
	    boolean signed = false;
	    boolean bigEndian = false; //?
	    AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);

	    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
	    if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }
	    
	    int bufferSize = 8192;
	    byte buffer[] = new byte[bufferSize];
		double real[] = new double[bufferSize];
		double imag[] = new double[bufferSize];
	    
		double freqTable[] = new double[bufferSize];
		for (int i=0; i<bufferSize; ++i)
			freqTable[i] = (sampleRate * i)/bufferSize;
		
	    TargetDataLine line;
	    try {
			line = (TargetDataLine) AudioSystem.getLine(info);
			line.open(format);
		    line.start();
			while (true) {
				int count = line.read(buffer, 0, buffer.length);
				if (count > 0) {
					for (int i = 0; i < count; i++) {
			            real[i] = buffer[i];
			            imag[i] = 0;
					}
					
					Fft.transform(real, imag);
					
					double maxFreq = 0;
					int maxInd = 0;
					double abs;
					for (int i=0; i<real.length/2; i++) {
						abs = real[i]*real[i] + imag[i]*imag[i];
						if (abs > maxFreq) {
							maxFreq = abs;
							maxInd = i;
						}
					}
					System.out.println("F=" + freqTable[maxInd] + ", " + Notes.findNote(freqTable[maxInd]));
				}
			}
//			line.stop();
//			line.close();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Tuner t = new Tuner();
		t.tune("C3");
	}
	
}
